﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CyzFaceBLL.Common
{
    public class Tool
    {
        /// <summary>
        /// 两个时间点相差的秒数
        /// </summary>
        /// <param name="dtStart">起始时间点</param>
        /// <param name="dtEnd">截至时间点</param>
        /// <returns></returns>
        public static long DiffSeconds(DateTime dtStart, DateTime dtEnd)
        {
            try
            {
                long lDiff = Math.Abs((dtEnd.Ticks - dtStart.Ticks) / 10000000);
                return lDiff;
            }
            catch { }
            return 0;
        }

        /// <summary>
        /// 两个时间点相差的毫秒数
        /// </summary>
        /// <param name="dtStart"></param>
        /// <param name="dtEnd"></param>
        /// <returns></returns>
        public static long DiffMilliseconds(DateTime dtStart, DateTime dtEnd)
        {
            try
            {
                TimeSpan span = (TimeSpan)(dtEnd - dtStart);
                return Math.Abs(span.Milliseconds);
            }
            catch { }
            return 0;
        }


        /// <summary>
        /// 获取与添加配置文件某项的内容
        /// </summary>
        /// <param name="item">参数项内容</param>
        /// <param name="value">添加时的默认值</param>
        /// <returns></returns>
        public static string GetAndAddConfig(string item, string value)
        {
            try
            {
                //获取Configuration对象
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                //根据Key读取<add>元素的Value
                string sValue = "";
                try
                {
                    sValue = config.AppSettings.Settings[item].Value;
                }
                catch { }

                ////写入<add>元素的Value
                //config.AppSettings.Settings["name"].Value = "xiao";

                if (string.IsNullOrEmpty(sValue))
                {
                    //增加<add>元素
                    config.AppSettings.Settings.Add(item, value);
                }
                else
                {
                    value = sValue;
                }

                ////删除<add>元素
                //config.AppSettings.Settings.Remove("name");

                //一定要记得保存，写不带参数的config.Save()也可以
                config.Save(ConfigurationSaveMode.Modified);

                //刷新，否则程序读取的还是之前的值（可能已装入内存）
                ConfigurationManager.RefreshSection("appSettings");

                return value;
            }
            catch { }
            return "";
        }

        /// <summary>
        /// 程序配置文件配置信息保存
        /// </summary>
        /// <param name="item"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SaveConfig(string item, string value)
        {
            bool bResult = false;
            try
            {
                if (string.IsNullOrEmpty(value))
                {
                    value = " ";
                }
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings[item].Value = value;
                ConfigurationManager.AppSettings[item] = value;
                config.Save(ConfigurationSaveMode.Modified);
                try
                {
                    //刷新，否则程序读取的还是之前的值（可能已装入内存）
                    ConfigurationManager.RefreshSection("appSettings");
                }
                catch { }
                bResult = true;
            }
            catch { }
            return bResult;
        }

        /// <summary>
        /// 获取配置文件某项的内容
        /// </summary>
        /// <param name="ParamName"></param>
        /// <returns></returns>
        public static string GetConfig(string ParamName)
        {
            try
            {
                string str = ConfigurationManager.AppSettings[ParamName].ToString().Trim();
                return str;
            }
            catch { }
            return "";
        }

        /// <summary>
        /// 格式化json字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertJsonString(string str)
        {
            try
            {
                JsonSerializer serializer = new JsonSerializer();
                TextReader tr = new StringReader(str);
                JsonTextReader jtr = new JsonTextReader(tr);
                object obj = serializer.Deserialize(jtr);
                if (obj != null)
                {
                    StringWriter textWriter = new StringWriter();
                    JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                    {
                        Formatting = Formatting.Indented,
                        Indentation = 4,
                        IndentChar = ' '
                    };
                    serializer.Serialize(jsonWriter, obj);
                    return textWriter.ToString();
                }
                else
                {
                    return str;
                }
            }
            catch { }
            str = LogBase64JsonDataRemoval(str);
            return str;
        }

        /// <summary>
        /// 以Json为格式的日志中的图片Base64数据去除
        /// </summary>
        /// <param name="sLog"></param>
        /// <returns></returns>
        public static string LogBase64JsonDataRemoval(string sLog)
        {
            try
            {
                string str = sLog;
                Regex re = new Regex("(?<=\").*?(?=\")", RegexOptions.None);
                MatchCollection mc = re.Matches(str);
                foreach (Match ma in mc)
                {
                    if (ma.Value.Length >= 1000)
                    {
                        str = str.Replace(ma.Value, "『Img』数据长度 = " + ma.Value.Length.ToString());
                    }
                }
                return str;
            }
            catch { }
            return sLog;
        }

        /// <summary>
        /// MD5加密(32位)
        /// </summary>
        /// <param name="str">加密字符</param>
        /// <returns></returns>
        public static string EncryptWithMD5By32(string str)
        {
            string cl = str;
            string pwd = "";
            try
            {
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
                for (int i = 0; i < s.Length; i++)
                {
                    pwd = pwd + s[i].ToString("X2");
                }
            }
            catch { }
            return pwd;
        }

    }
}
